package cn.edu.swu.lzr.Safe;

import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class LogFilter extends HttpFilter {


    public static final String StatusFilter = "STATUSFilter";
    public static final String INIT_PARAM_IGNORE_URLS = "ignoreUrls";
    private String[] ignoreUrls = null;

    public void init(FilterConfig filterConfig) {
        String urls = filterConfig.getInitParameter(INIT_PARAM_IGNORE_URLS);
        if (urls != null) {
            this.ignoreUrls = urls.split(";");
        }

    }

    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = request.getRequestURI();

        for (String ignoreUrl : this.ignoreUrls) {
            if (uri.endsWith(ignoreUrl)) {
                chain.doFilter(request, response);
                return;
            }
        }

        HttpSession session = request.getSession(true);
        cn.edu.swu.lzr.Safe.StatusFilter statusFilter = (StatusFilter) session.getAttribute(StatusFilter);
        if ( statusFilter != null && statusFilter.equals(cn.edu.swu.lzr.Safe.StatusFilter.LOGIN_SUCCESS))
        {
            chain.doFilter(request,response);
            return;
        }
        else {
            response.sendRedirect("./index.html");
        }
    }
}

